package crossbreed.presenters;

import java.awt.Color;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.util.ArrayList;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import crossbreed.models.ComparisonModel.ComparisonLine;
import crossbreed.models.ComparisonModel.ComparisonModelListener;
import crossbreed.models.ComparisonModel.IComparisonModel;
import crossbreed.models.ComparisonModel.LineType;
import crossbreed.views.IFileView;

public class RightFilePresenter implements ComparisonModelListener, DocumentListener, AdjustmentListener
{
	private IFileView view;
	private IFileView leftView;
	private IComparisonModel model;
	
	public RightFilePresenter(IComparisonModel model)
	{
		this.model = model;
		model.addListener(this);
	}

	public void setView(IFileView view)
	{
		this.view = view;
	}
	
	public void setLeftView(IFileView leftView)
	{
		this.leftView = leftView;
	}

	@Override
	public void diffCreationComplete()
	{
		try
		{
			int currentCharIndex = 0;
			DefaultStyledDocument document = new DefaultStyledDocument();
			ArrayList<ComparisonLine> lines = model.getRightLines();
			Color background = Color.BLACK;
			SimpleAttributeSet set = new SimpleAttributeSet();
			
			for (ComparisonLine line : lines)
			{
				if (line.lineType == LineType.SAME) background = Color.BLACK;
				else if (line.lineType == LineType.SWAP) background = Color.BLUE;
				else if (line.lineType == LineType.DELETE) background = Color.RED;
				else background = Color.GREEN;

				document.insertString(currentCharIndex, line.line + "\r\n", set);
				int startIndex = currentCharIndex;
				currentCharIndex += line.line.length() + 2;
				
				if (line.lineType != LineType.SAME) view.addHighlight(startIndex, background);
			}
			
			view.displayDocument(document);
			document.addDocumentListener(this);
		}
		catch (Exception e)
		{
		}
	}

	@Override
	public void diffCreationFailed(String message)
	{
		
	}

	@Override
	public void changedUpdate(DocumentEvent e)
	{

	}

	@Override
	public void insertUpdate(DocumentEvent e)
	{
		view.updateHighlights(e.getOffset(), e.getLength());
	}

	@Override
	public void removeUpdate(DocumentEvent e)
	{
		view.updateHighlights(e.getOffset(), -e.getLength());
	}

	@Override
	public void adjustmentValueChanged(AdjustmentEvent e)
	{
		leftView.scrollToPosition(e.getValue());
	}
}
